package com.lzp.java.concurrent.buildcache;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lzp
 * @Description: 1. 使用ConcurrentHashMap保证线程安全，但是会出现重复计算问题
 * @date 2021/3/14
 */
public class Cache3<K, V> implements Computable<K, V> {
    private final Map<K, V> cache = new ConcurrentHashMap<>();
    private final Computable<K, V> c;

    public Cache3(Computable<K, V> c) {
        this.c = c;
    }

    @Override
    public V compute(K key) throws Exception {
        V result = cache.get(key);
        if (result == null) {
            result = c.compute(key);
            cache.put(key, result);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        Cache3<String, Integer> cache1 = new Cache3<>(new ComputableImpl());
        System.out.println(cache1.compute("key"));
        System.out.println(cache1.compute("key"));
    }
}
